package com.example.weatherapp1.data.repository



import com.example.weatherapp1.data.local.CityDao
import com.example.weatherapp1.data.local.WeatherDao
import com.example.weatherapp1.data.model.City
import com.example.weatherapp1.data.model.SavedWeather
import com.example.weatherapp1.data.model.WeatherResponse
import com.example.weatherapp1.data.remote.WeatherApiService
import com.google.gson.Gson
import javax.inject.Inject


class WeatherRepository @Inject constructor(
    private val weatherApiService: WeatherApiService,
    private val weatherDao: WeatherDao,
    private val cityDao: CityDao,
    private val gson: Gson
) {
    // 从网络获取天气数据
    suspend fun fetchWeather(latitude: Double, longitude: Double): WeatherResponse {
        val response = weatherApiService.getWeather(latitude, longitude)
        if (response.isSuccessful) {
            return response.body() ?: throw Exception("Empty response body")
        } else {
            throw Exception("Failed to fetch weather: ${response.message()}")
        }
    }

    // 保存天气数据到本地
    suspend fun saveWeather(cityId: Int, weatherResponse: WeatherResponse) {
        val weatherJson = gson.toJson(weatherResponse)
        val savedWeather = SavedWeather(
            cityId = cityId,
            temperature = weatherResponse.result.realtime.temperature,
            skyCon = weatherResponse.result.realtime.skyCon,
            updateTime = System.currentTimeMillis(),
            weatherJson = weatherJson
        )

        // 先删除该城市的旧数据
        weatherDao.deleteWeatherByCityId(cityId)
        // 插入新数据
        weatherDao.insertWeather(savedWeather)
    }

    // 获取城市的最新天气
    fun getLatestWeatherByCityId(cityId: Int) =
        weatherDao.getLatestWeatherByCityId(cityId)

    // 获取城市列表
    fun getAllCities() = cityDao.getAllCities()

    // 添加城市
    suspend fun addCity(city: City) {
        cityDao.insertCity(city)
    }

    // 更新城市
    suspend fun updateCity(city: City) {
        cityDao.updateCity(city)
    }

    // 删除城市
    suspend fun deleteCity(cityId: Int) {
        cityDao.deleteCity(cityId)
        // 同时删除该城市的天气数据
        weatherDao.deleteWeatherByCityId(cityId)
    }

    // 设置当前位置城市
    suspend fun setCurrentLocationCity(city: City) {
        // 先重置所有城市的当前位置标记
        cityDao.resetCurrentLocation()
        // 设置新的当前位置城市
        cityDao.updateCity(city.copy(isCurrentLocation = true))
    }

    // 获取当前位置城市
    suspend fun getCurrentLocationCity() = cityDao.getCurrentLocationCity()
}
